/*
 * Copyright 2011 myTDev.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mytdev.commons.text;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author Yann D'Isanto
 */
public abstract class AbstractParserFactory implements ParserFactory {
    
    private final Map<Class<?>, Parser<?>> parsers = new HashMap<Class<?>, Parser<?>>();

    @Override
    public boolean isTypeSupported(Class<?> type) {
        return getMoreSpecialisedSupportedType(type) != null;
    }

    @Override
    public <T> Parser<? extends T> getParser(Class<T> type) throws IllegalArgumentException {
        Parser<? extends T> parser = getMoreSpecialisedSupportedTypeParser(type);
        if(parser == null) {
            throw new IllegalArgumentException("unsupported type: " + type.getName());
        }
        return parser;
    }
    
    protected <T> void putParser(Class<T> type, Parser<? extends T> parser) {
        if(type == null) {
            throw new NullPointerException("type is null");
        }
        if(parser == null) {
            throw new NullPointerException("parser is null");
        }
        parsers.put(type, parser);
    }

    protected <T> void removeParser(Class<T> type) {
        parsers.remove(type);
    }
    
    protected <T> void removeAllParsers(Class<T> type) {
        parsers.clear();
    }
    
    private <T> Class<? extends T> getMoreSpecialisedSupportedType(Class<T> type) {
        Class<? extends T> moreSpecialisedType = null;
        for (Class<?> supportedType : parsers.keySet()) {
            if(type.isAssignableFrom(supportedType)) {
                if(moreSpecialisedType == null || moreSpecialisedType.isAssignableFrom(supportedType)) {
                    moreSpecialisedType = (Class<? extends T>) supportedType;
                }
            }
        }
        return moreSpecialisedType;
    }
    
    private <T> Parser<? extends T> getMoreSpecialisedSupportedTypeParser(Class<T> type) {
        return (Parser<? extends T>) parsers.get(getMoreSpecialisedSupportedType(type));
    }
    
}
